function readTxt() {
	document.getElementById("uploadFile").click();
	readLocalFile();
}

function readLocalFile() {
	var localFile = document.getElementById("uploadFile").files[0];
	if (localFile.length == 0) {
		return false;
	}
	if (localFile.type.indexOf('text/plain') === -1) {
		alert("您选择的不是txt文档！");
		return false;
	}
	document.getElementById("txtFile").innerHTML = localFile.name
	var reader = new FileReader();
	reader.readAsBinaryString(localFile);
	var type;
	reader.onloadstart = function(event) {
		document.getElementById("topDiv").style.display = "block"
	}
	reader.onload = function(event) {
		var jschardet = require("jschardet");
		type = jschardet.detect(this.result).encoding;
		if ("GB2312" == type || "GBK" == type) {
			type = "GB18030"
		}
		var read = new FileReader();
		read.readAsText(localFile, type);
		read.onload = function(f) {
			document.getElementById("title").value = "";
			document.getElementById("author").value = "";
			document.getElementById("lable").value = "";
			document.getElementById("chapterSize").value = ""
			$("#intro").empty()
			$("#chapter").empty()
			$("#fileContent").text("");
			content = f.target.result;
			$("#fileContent").text(content);
			document.getElementById("topDiv").style.display = "none";
			$("#drop_area").html("");
		}

	}
	reader.onerror = function(event) {
		alert("File could not be read! Code " + event.target.error.code);
		document.getElementById("topDiv").style.display = "none"
	}
}

function jiexi() {
	var content = $("#fileContent").text();
	if (content == "") {
		alert("请先选择文件,再进行解析")
		return false
	}
	document.getElementById("jieTopDiv").style.display = "block"
	var arry = content.split("\n");
	var reg;
	for (var authori = 0; authori < arry.length; authori++) {
		//作者
		var authorStr = "(【|\\[).*?作者.*?(:|：).*?(\\]|】)";
		reg = new RegExp(authorStr);
		if (reg.test(arry[authori])) {
			var str = arry[authori];
			var reg = /[^(：|:)]*(：|:)*/;
			str = str.replace(reg, "$1").replace("]", "").replace(":", "").replace("：", "");
			document.getElementById("author").value = str;
			break
		}
	}
	for (var titlei = 0; titlei < arry.length; titlei++) {
		//标题
		var titleStr = "(【|\\[).*?(标题|书名).*?(:|：).*?(\\]|】)";
		reg = new RegExp(titleStr);
		if (reg.test(arry[titlei])) {
			var str = arry[titlei];
			var reg = /[^(：|:)]*(：|:)*/;
			str = str.replace(reg, "$1").replace("]", "").replace(":", "").replace("：", "");
			document.getElementById("title").value = str
			break
		}
	}
	for (var lablei = 0; lablei < arry.length; lablei++) {
		//标签
		var lableStr = "(【|\\[)标签(:|：)[\\s\\S]*?(\\]|】)";
		reg = new RegExp(lableStr);
		if (reg.test(arry[lablei])) {
			var str = arry[lablei];
			var reg = /[^(：|:)]*(：|:)*/;
			str = str.replace(reg, "$1").replace("]", "").replace(":", "").replace("：", "");
			document.getElementById("lable").value = str
			break
		}
	}
	$("#intro").empty()
	for (var i = 0; i < arry.length; i++) {
		//简介
		var introStr = "(【|\\[)(内容简介\|简介)(:|：)[\\s\\S]*?(\\]|】)";
		reg.compile(introStr);
		if (reg.test(arry[i])) {
			if (arry[i].trim().length < 10) {
				var biaoshi = arry[i + 1].trim()
				if (typeof biaoshi == "undefined" || biaoshi == null || biaoshi == "") {
					var s = 2;
					for (;;) {
						var biaoshi1 = arry[i + s].trim();
						if (typeof biaoshi1 == "undefined" || biaoshi1 == null || biaoshi1 == "") {
							break;
						}
						$("#intro").append(biaoshi1)
						s++;
					}
				} else {
					var nextPage = 1;
					for (;;) {
						var biaoshi1 = arry[i + nextPage].trim();
						if (typeof biaoshi1 == "undefined" || biaoshi1 == null || biaoshi1 == "") {
							break;
						}
						$("#intro").append(biaoshi1)
						nextPage++;
					}
				}
			}
		}
	}
	$("#chapter").empty()
	var result = {}
	result.list = {}
	var resultList = 0
	var contentType = 0;
	for (var i = 0; i < arry.length; i++) {
		//章节列表
		if (matchTitle(arry[i])) {
			if (resultList != 0) {
				resultList++
			}
			if (contentType == 2 && resultList == 0) {
				resultList++
			}
			result.list[resultList] = {}
			result.list[resultList].title = arry[i].trim()
			result.list[resultList].ordernum = resultList + 1
			result.list[resultList].content = " "
			$("#chapter").append(arry[i].trim() + "\n")
			contentType = 1
		}
		var nowArry = arry[i]
		if (typeof nowArry == "undefined" || nowArry == null || nowArry == "") {
			continue;
		}
		if (contentType == 1) {
			contentType = 2
			continue
		}
		if (contentType == 2) {
			result.list[resultList].content += "<p>" + arry[i].trim() + "</p>"
		}
	}
	$("#resultContent").text(JSON.stringify(result));
	$("#chapterSize").val(resultList + 1)
	document.getElementById("jieTopDiv").style.display = "none"
}

function matchTitle(str) {
	var regexStr =
		"((第)?(一|二|两|三|四|五|六|七|八|九|十|百|[0-9]|千|零){1,8}(章|卷|回|集|节))|(正文)|(导读)|(前言)|(序言)|(后记)|(楔子)|(番外)|(附录)|((C|c)hapter([0-9]{1,5}))|((P|p)art([0-9]{1,5}))";
	// Pattern p = Pattern.compile(regexStr);
	var reg = new RegExp(regexStr);
	var exclueReg = //205圣上说布和银子是一回事吗？   ☆、1042公主说，我要去看我爹    
		"(((p|P)(s|S)))|(更新)|((第|这|又|下|上|头|有|干)(一|二|两|三|四|五|六|七|八|九|十|百|[0-9])(回|篇|节|更))|((这|又|下|上|头|有)?一(起|边|旁|回|章|篇|节)(家|庙|房|神|府|到|头|看|来|事|复|归|背|节))|(回复)|(几百回)|.com";
	// Pattern execlueP = Pattern.compile(exclueReg);
	var execlup = new RegExp(exclueReg);
	if (str == null || str.trim().length == 0) {
		return false;
	}
	if (reg.test(str)) {
		// 匹配了标题，如果用匹配正则 把这个标题分割，其数组第一个元素的长度不应该超过1
		var spiltArr = new Array(2);

		spiltArr[0] = str.substring(0, reg.exec(str).index);
		var patt = new RegExp(regexStr, "g");
		patt.exec(str);
		var firstIndex = reg.exec(str).index;
		spiltArr[1] = str.substring(reg.exec(str).index + (patt.lastIndex - firstIndex));

		if (spiltArr.length > 0) {
			// 匹配 exclueReg 的正则，说明 不是章节标题
			var oneLeng = spiltArr[0].length + (patt.lastIndex - firstIndex) + 2;
			var oneStr = str.substring(0, oneLeng > str.length ? oneLeng - 2 : oneLeng);
			if (execlup.test(oneStr)) {
				return false;
			}
			var spiltOne = spiltArr[0].trim().replace(/( |　)/g, ""); // 替换
			// 英文空格
			// 和全角空格
			if (spiltOne.length > 1) { // 长度不应该超过1
				return false;
			}
		}
		if (spiltArr.length > 1) {
			// 标题字数限制
			if (spiltArr[1].trim().replace(/( |　)/, "").length > 28) {
				return false;
			}
		}
		//判断“一回”的后面跟随的不是“空格”或“.”，就不是图书章节标题
		var huiRegP = new RegExp("(一回[^　  .]{1,})");
		// 					Pattern huiRegP = Pattern.compile("(一回[^　  .]{1,})");
		// 					Matcher huiRegMatcher = huiRegP.matcher(str);
		if (huiRegP.test(str)) {
			return false;
		}
		return true;
	}
	return false;
}

function readImg() {
	document.getElementById("imgFile").click();
}

function imgChange() {
	if (document.getElementById("imgFile").files[0].type.indexOf('image') === -1) {
		alert("您选择的不是图片!")
		document.getElementById("imgFile").value = ''
	} else {
		var img = window.URL.createObjectURL(document.getElementById("imgFile").files[0]);
		var str = "<img style='width:100%;height:100%' id='fengMianImg' src='" + img + "'>";
		$("#drop_area").html(str);
	}
}

function saveContent() {
	var title = $("#title").val();
	var author = $("#author").val();
	var lable = $("#lable").val();
	var intro = $("#intro").val();
	var category = $("#fenlei").val();
	var category_id = $("#fenlei_id").val();
	var resultContent = $("#resultContent").text();
	if (title == "" || title == "undefined" || title == null) {
		alert("文章标题请正确填写!!!");
	} else if (author == "" || author == "undefined" || author == null) {
		alert("文章作者请正确填写!!!");
	} else if (lable == "" || lable == "undefined" || lable == null) {
		alert("文章标签请正确填写!!!");
	} else if (intro == "" || intro == "undefined" || intro == null) {
		alert("文章简介请正确填写!!!");
	} else if (category == "" || category == "undefined" || category == null) {
		alert("文章分类请选择!!!");
	} else {
		var bookJson = {};
		bookJson.name = title
		bookJson.author = author
		bookJson.description = intro
		bookJson.type = category
		resultContent = JSON.parse(resultContent)
		var chapArrJson = resultContent
		var imgFile = document.getElementById("imgFile").files[0];
		// var coverFile = new FormData(imgFile);
		console.log(JSON.stringify(bookJson))
		console.log(JSON.stringify(chapArrJson.list))
		console.log(imgFile)
		imgUpload(bookJson,chapArrJson,imgFile)
// 		resultContent.name = title
// 		resultContent.author = author
// 		// resultContent.lable = lable
// 		resultContent.description = intro
// 		resultContent.type = category
		// console.log(JSON.stringify(resultContent))
		// $("#result").val(JSON.stringify(resultContent))
	}
}

function imgUpload(bookJson,chapArrJson,coverFile) {
	console.log(1)
	$.ajax({
		url : "http://192.168.1.246:9090/app/book/save",
		type : "post",
// 		processData : false,
// 		contentType : false,
		contentType : 'jsonp',
		data : {
			bookJson : JSON.stringify(bookJson),
			chapArrJson : JSON.stringify(chapArrJson.list),
			coverFile : coverFile
		} ,
		success: function(response, status,xhr){
			console.log('状态为：' + status + ',状态是：' + xhr.statusText);
			console.log(response);
		}
	});
	console.log(2)
}

function toFenlei() {
	window.open("fenlei.html");
}
